package com.qixia.sportsupload.util;

/**
 * @Author Administrator
 * @Date 2023/12/12
 * @Description
 */

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author Sven
 */
@Slf4j
public class FileUtils {
    private static final int BUFFER_SIZE = 1024;
    private static final String DEFAULT_FILE_ENCODING = "utf-8";

    public static boolean fileIsExists(String path) {
        File f = new File(path);
        if (f.isFile()) {
            return f.exists();
        } else {
            return false;
        }
    }

    public static boolean createFile(String destFileName) {
        File file = new File(destFileName);
        if (file.exists()) {
            log.info("创建单个文件" + destFileName + "失败，目标文件已存在");
            return false;
        }
        if (destFileName.endsWith(File.separator)) {
            log.info("创建单个文件" + destFileName + "失败，目标文件不能为目录");
            return false;
        }
        if (!file.getParentFile().exists()) {
            log.info("目标文件所在目录不存在，准备创建它。");
            if (!file.getParentFile().mkdirs()) {
                log.info("创建目标文件所在目录失败！");
                return false;
            }
        }
        // 创建目标文件
        try {
            if (file.createNewFile()) {
                log.info("创建单个文件" + destFileName + "成功。");
                return true;
            } else {
                log.info("创建单个文件" + destFileName + "失败。");
                return false;
            }
        } catch (IOException e) {
            log.info("创建单个文件" + destFileName + "失败。", e);
            return false;
        }
    }

    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {
            destDirName = destDirName + File.separator;
        }
        // 创建目录
        if (dir.mkdirs()) {
            log.info("创建目录" + destDirName + "成功。");
            return true;
        } else {
            log.info("创建目录" + destDirName + "失败。");
            return false;
        }
    }

    public static String createTempFile(String prefix, String suffix,
                                        String dirName) {
        File tempFile = null;
        if (dirName == null) {
            try {
                tempFile = File.createTempFile(prefix, suffix);
                return tempFile.getCanonicalPath();
            } catch (IOException e) {

                log.info("创建临时文件失败。" + e.getMessage());
                return null;
            }
        } else {
            File dir = new File(dirName);
            if (!dir.exists()) {
                if (!createDir(dirName)) {
                    log.info("创建临时文件失败，不能创建临时文件所在的目录。");
                    return null;
                }
            }
            try {
                // 在指定目录下创建临时文件
                tempFile = File.createTempFile(prefix, suffix, dir);
                return tempFile.getCanonicalPath();
            } catch (IOException e) {
                log.info("创建临时文件失败。" + e.getMessage());
                return null;
            }
        }
    }

    /**
     * 使用文件通道的方式复制文件
     *
     * @param sName 源文件
     * @param tName 复制到的新文件
     */
    public static void fileChannelCopy(String sName, String tName) {
        File s = new File(sName);
        File t = new File(tName);
        if (!s.exists()) {
            log.error("源文件不存在：" + sName);
            throw new IllegalStateException("源文件不存在：" + sName);
        }
        try (FileInputStream fi = new FileInputStream(s);
             FileOutputStream fo = new FileOutputStream(t);
             FileChannel in = fi.getChannel();
             FileChannel out = fo.getChannel()) {
            in.transferTo(0, in.size(), out);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }


    public static String read(String fileName) {
        return read(fileName, DEFAULT_FILE_ENCODING);
    }

    public static String read(String fileName, String encoding) {
        try (InputStream inputStream = Files.newInputStream(Paths.get(fileName));
             InputStreamReader inputReader = new InputStreamReader(inputStream, encoding);
             BufferedReader bufferReader = new BufferedReader(inputReader)) {
            String line;
            StringBuilder strBuffer = new StringBuilder();
            while ((line = bufferReader.readLine()) != null) {
                strBuffer.append(line).append("\n");
            }
            return strBuffer.toString();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return "";
    }

    public static void write(String name, String content) {
        write(name, content, DEFAULT_FILE_ENCODING);
        log.info("写入成功");
    }

    public static void write(String name, String content, String encoding) {
        File file = new File(name);
        try (BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(
                Files.newOutputStream(file.toPath()), encoding))) {
            fw.write(content);
            fw.flush(); // 全部写入缓存中的内容
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 下载文件
     *
     * @param request   请求
     * @param response  响应
     * @param storePath 存储路径
     * @param realName  原文件名
     * @throws Exception
     */
    public static void download(HttpServletRequest request, HttpServletResponse response, String storePath,
                                String realName) throws Exception {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        BufferedInputStream bis;
        BufferedOutputStream bos;
        String contentType = "application/octet-stream";

        String ctxPath = request.getSession().getServletContext().getRealPath("/");

        String downLoadPath = ctxPath + "\\" + storePath;

        long fileLength = new File(downLoadPath).length();

        response.setContentType(contentType);
        response.setHeader("Content-disposition", "attachment; filename="
                + new String(realName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(fileLength));
        bis = new BufferedInputStream(new FileInputStream(downLoadPath));
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        bis.close();
        bos.close();
    }

    public static String getRandomString(int num) {
        String str = "abcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < num; i++) {
            res.append(str.charAt((int) (Math.random() * 36)));
        }
        return res.toString();
    }
}
